<template>
  <a-drawer
    :title="title"
    placement="right"
    :closable="false"
    :visible="visible"
    @close="onClose"
    destroyOnClose
    :width="950"
    :headerStyle="{ position: 'fixed', top: 0, width: '100%', background: '#fff', zIndex: 2 }"
    :body-style="{ paddingBottom: '80px' }"
  >
    <a-form @submit="handleSubmit" :form="form" :labelCol="{ lg: { span: 5 }, sm: { span: 7 } }" :wrapperCol="{ lg: { span: 15 }, sm: { span: 17 } }" style="padding-top: 60px">
      <a-form-item label="标题">
        <a-input v-decorator="['name', { rules: [{ required: true, message: '请输入标题！', whitespace: true, max: 36 }] }]" :max-length="36" name="name" placeholder="请输入" autocomplete="off" />
      </a-form-item>
      <a-form-item label="活动类型" required="">
        <a-select v-decorator="['type']" placeholder="请选择" :getPopupContainer="triggerNode => triggerNode.parentNode" show-search :filter-option="filterOption">
          <a-select-option :value="item.value" v-for="(item, index) in typeList" :key="index">{{ item.title }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="红包页面背景图" required>
        <JImageUpload :uploadParams="uploadParams" :isMultiple="false" :accept="'image/*'" @fileChange="e => fileChange(e, 'backgroundUrl')" v-model="backgroundUrl"></JImageUpload>
        <div class="tip" v-show="tips.backgroundUrl">请上传图片！</div>
      </a-form-item>
      <a-form-item label="未拆封红包图" required>
        <JImageUpload :uploadParams="uploadParams" :isMultiple="false" :accept="'image/*'" @fileChange="e => fileChange(e, 'unOpenImg')" v-model="unOpenImg"></JImageUpload>
        <div class="tip" v-show="tips.unOpenImg">请上传图片！</div>
      </a-form-item>
      <a-form-item label="失效红包图" required>
        <JImageUpload :uploadParams="uploadParams" :isMultiple="false" :accept="'image/*'" @fileChange="e => fileChange(e, 'noUseImg')" v-model="noUseImg"></JImageUpload>
        <div class="tip" v-show="tips.noUseImg">请上传图片！</div>
      </a-form-item>
      <a-form-item label="已抢完红包图" required>
        <JImageUpload :uploadParams="uploadParams" :isMultiple="false" :accept="'image/*'" @fileChange="e => fileChange(e, 'doneImg')" v-model="doneImg"></JImageUpload>
        <div class="tip" v-show="tips.doneImg">请上传图片！</div>
      </a-form-item>
      <a-form-item label="页面背景色值">
        <a-input v-decorator="['color', { rules: [{ required: true, message: '请输入标题！', whitespace: true }] }]" name="name" placeholder="请输入" autocomplete="off" />
      </a-form-item>
      <a-form-item label="红包内优惠券" required>
        <a-button type="primary" @click="openCoupons"><a-icon type="plus" />添加</a-button>
        <span class="tip" v-show="vouchersTip" style="margin-left:12px">请选择优惠券</span>
        <!-- <a-tooltip>
          <template slot="title" v-if="actObj.vouchersList && actObj.vouchersList.length > 2">
            {{ vouchersName(actObj.vouchersList, coupons) }}
          </template>
          <a-select
            mode="multiple"
            :maxTagCount="2"
            autoClearSearchValue
            show-search
            allowClear
            v-decorator="['vouchersList', { rules: [{ required: true, message: '请选择！' }] }]"
            placeholder="请选择"
            :filter-option="filterOption"
            @change="changeVouchers"
            :getPopupContainer="triggerNode => triggerNode.parentNode"
          >
            <a-select-option v-for="(item, index) in coupons" :key="index" :value="item.id">{{ item.name }}</a-select-option>
          </a-select>
        </a-tooltip> -->
      </a-form-item>
      <div style="margin-bottom:24px"><CouponTable ref="vouchersTable" @updateCoupons="updateCoupons"></CouponTable></div>
      <a-form-item label="数量">
        <a-input
          v-decorator="['nums', { rules: [{ required: true, pattern: /^[1-9]\d*$/, message: '请输入有效期，且是正整数！', whitespace: true }] }]"
          name="name"
          placeholder=" 请输入"
          autocomplete="off"
        />
      </a-form-item>
      <a-form-item label="起止日期">
        <a-range-picker
          format="YYYY-MM-DD HH:mm:ss"
          :show-time="{ defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('00:00:00', 'HH:mm:ss')] }"
          v-decorator="['timepicker', { rules: [{ required: true, message: '请选择时间！' }] }]"
        />
      </a-form-item>
      <a-form-item label="活动规则">
        <a-textarea rows="8" placeholder="请输入" :max-length="300" v-decorator="['rule', { rules: [{ required: true, max: 300, message: '请输入介绍，不超过300个字符！' }] }]" />
      </a-form-item>
      <a-form-item label="小程序卡片标题">
        <a-input
          v-decorator="['cardSubject', { rules: [{ required: true, message: '请输入标题！', whitespace: true, max: 36 }] }]"
          :max-length="36"
          name="name"
          placeholder="请输入"
          autocomplete="off"
        />
      </a-form-item>
      <a-form-item label="小程序卡片缩略图" required>
        <JImageUpload :uploadParams="uploadParams" :isMultiple="false" :accept="'image/*'" @fileChange="e => fileChange(e, 'cardImg')" v-model="cardImg"></JImageUpload>
        <div class="tip" v-show="tips.cardImg">请上传图片！</div>
      </a-form-item>
      <a-form-item label="状态">
        <a-radio-group name="radioGroup" v-decorator="['status', { rules: [{ required: true, message: '请选择！' }] }]">
          <a-radio :value="1">上架</a-radio>
          <a-radio :value="0">下架</a-radio>
        </a-radio-group>
      </a-form-item>
      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1
        }"
      >
        <a-button :style="{ marginRight: '8px' }" @click="onClose">取消</a-button>
        <a-button type="primary" htmlType="submit">确定</a-button>
      </div>
    </a-form>
    <CouponModal ref="couponModal" @handleAddCoupons="handleAddCoupons"></CouponModal>
  </a-drawer>
</template>
<script>
import JImageUpload from '@/components/qiniuUpload/JImageUpload.vue'
import moment from 'moment'
import 'moment/locale/zh-cn'
import pick from 'lodash.pick'
import { activityDetail, activityCreate, couponList } from '@/api/box/setting'
import { forEach } from 'lodash'
import CouponTable from '@/views/box/components/couponModal/couponTable'
import { CouponModal } from '@/views/box/components'
export default {
  props: ['coupons', 'typeList', 'uploadParams'],
  components: {
    JImageUpload,
    CouponTable,
    CouponModal
  },
  data() {
    return {
      moment,
      title: '',
      visible: false,
      spinning: true,
      form: this.$form.createForm(this),
      actId: '',
      vouchers: [],
      actObj: {},
      vouchersList: [],
      imgObj: {
        backgroundUrl: [],
        doneImg: [],
        noUseImg: [],
        unOpenImg: [],
        cardImg: []
      },
      tips: {
        backgroundUrl: false,
        doneImg: false,
        noUseImg: false,
        unOpenImg: false,
        cardImg: false
      },
      vouchersTip: false,
      backgroundUrl: [],
      doneImg: [],
      noUseImg: [],
      unOpenImg: [],
      cardImg: []
    }
  },
  computed: {
    vouchersName(list, coupons) {
      return (list, coupons) => {
        let arr = coupons.filter(e => list.includes(e.id))
        return arr.map(i => i.name).join(',')
      }
    }
  },
  methods: {
    show(id) {
      this.actId = id
      if (this.actId != 'add') {
        this.title = '编辑'
        this.fetchDetail()
      } else {
        this.title = '新增'
      }
      this.visible = true
    },
    onClose() {
      this.visible = false
      this.backgroundUrl = []
      this.doneImg = []
      this.noUseImg = []
      this.unOpenImg = []
      this.cardImg = []
      this.actObj = {}
      this.vouchersTip = false
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    fetchDetail() {
      let self = this
      let params = {
        requestData: {
          id: this.actId
        }
      }
      activityDetail(params).then(res => {
        if (res.code == 0) {
          let data = res.data
          data.vouchersList = data.vouchers.split(',')
          console.log(data.vouchersList)
          this.fetchCouponList(data.vouchersList)
          data.type = data.type + ''
          data.timepicker = [moment(data.startTime), moment(data.endTime)]
          this.actObj = data
          this.backgroundUrl = data.backgroundUrl ? [data.backgroundUrl] : []
          this.doneImg = data.doneImg ? [data.doneImg] : []
          this.noUseImg = data.noUseImg ? [data.noUseImg] : []
          this.unOpenImg = data.unOpenImg ? [data.unOpenImg] : []
          this.cardImg = data.cardImg ? [data.cardImg] : []
          this.$nextTick(() => {
            self.form.setFieldsValue(pick(data, 'name', 'type', 'color', 'nums', 'rule', 'cardSubject', 'status', 'timepicker'))
          })
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    fetchCouponList(list) {
      let params = {
        page: {
          pageSize: 100,
          pageNo: 1
        },
        requestData: {
          ruleIds: list
        }
      }
      return couponList(params).then(res => {
        if (res.code == 0) {
          this.vouchersList = res.data
          this.$refs.vouchersTable.setData(this.vouchersList)
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    fileChange(list, type) {
      switch (type) {
        case 'backgroundUrl':
          this.imgObj.backgroundUrl = list
          break
        case 'doneImg':
          this.imgObj.doneImg = list
          break
        case 'noUseImg':
          this.imgObj.noUseImg = list
          break
        case 'unOpenImg':
          this.imgObj.unOpenImg = list
          break
        case 'cardImg':
          this.imgObj.cardImg = list
          break
      }
    },
    /**
     * 选择优惠券
     */
    openCoupons() {
      this.$refs.couponModal.show()
    },
    handleAddCoupons(list) {
      let coupons = [...this.vouchersList, ...list]
      let newArr = coupons.filter((currentValue, currentIndex, sourceArr) => {
        return sourceArr.findIndex(x => x.id === currentValue.id) === currentIndex
      })
      this.vouchersList = newArr
      this.$refs.vouchersTable.setData(this.vouchersList)
    },
    updateCoupons(list) {
      this.vouchersList = list
    },
    changeVouchers(value) {
      console.log(value)
      this.actObj.vouchersList = value
    },
    // 提交
    handleSubmit(e) {
      e.preventDefault()
      let imgValidate = false
      let imgValue = {}
      Object.keys(this.tips).forEach(key => {
        if (this.imgObj[key].length > 0) {
          this.tips[key] = false
          imgValue[key] = this.imgObj[key][0].url
        } else {
          this.tips[key] = true
          imgValidate = true
        }
      })
      if (this.vouchersList.length == 0) {
        this.vouchersTip = true
        return
      }
      this.form.validateFields((err, values) => {
        if (!err && !imgValidate) {
          this.vouchersTip = false
          let formValue = JSON.parse(JSON.stringify(values))
          formValue.startTime = values.timepicker[0].format('YYYY-MM-DD HH:mm:ss')
          formValue.endTime = values.timepicker[1].format('YYYY-MM-DD HH:mm:ss')
          formValue.vouchers = this.vouchersList.map(e => e.id).join(',')
          delete formValue.timepicker
          delete formValue.vouchersList
          Object.assign(formValue, imgValue)
          console.log(formValue)
          this.submitForm(formValue)
        }
      })
    },
    submitForm(value) {
      let params = {
        requestData: value
      }
      if (this.actId != 'add') params.requestData.id = this.actId
      activityCreate(params).then(res => {
        if (res.code == 0) {
          this.$message.success('编辑成功！')
          this.onClose()
          this.$emit('editOk')
        } else {
          this.$message.warning(res.msg)
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.tip {
  color: #f5222d;
  line-height: 22px;
  margin-top: -8px;
}
</style>

